<?php

class FP_View_Helper_AppendJs {

   public function setView(Zend_View_Interface $pView){
      $this->view = $pView;
   }

   public function appendJs($pJs=null, $pModule=null){
      if (Zend_Registry::isRegistered('assets_js___'))
	 $js = Zend_Registry::get('assets_js___');
      else
	 $js = array();

      if ($pJs){
	 if (!$pModule)
	    $pModule = 'default';

	 if (array_key_exists($pModule, $js))
	    $module = $js[$pModule];
	 else
	    $module = array();


	 if (is_array($pJs))
	    $module = array_merge($pJs, $module);
	 else {
	    if (!in_array($pJs, $module))
	       array_unshift($module, $pJs);
	 }

	 $js[$pModule] = $module;

	 Zend_Registry::set('assets_js___', $js);
      } else {

	if (FP_Application::getStagingEnvironment() == STAGING_DEVEL){
	    $prevent_cache = '&' . time();
	} else
	    $prevent_cache = '';

	 foreach ($js as $module => $assets){
	    if ($module == 'default')
	       return "<script type=\"text/javascript\" src=\"{$this->view->assets}/scripts/js.php?include=" . implode(',', $assets) . "{$prevent_cache}\"></script>\n";
	    else
	       return "<script type=\"text/javascript\" src=\"{$this->view->assets}/$module/scripts/js.php?include=" . implode(',', $assets) . "{$prevent_cache}\"></script>\n";
	 }
      }

   }

}

?>